import { getFileLocalUrl, getFileName } from "@/utils/tools";
export default defineComponent({
  name: "UploadFile",
  props: {
    modelValue: {
      type: String,
      default: "",
    },
    accept: {
      // 接受的文件类型
      type: String,
      default:
        ".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    },
  },
  emits: ["update:modelValue"],
  setup(props, { attrs, emit, expose, slots }) {
    const fileList = ref<any>(
      props.modelValue
        ? [
            {
              uid: -1,
              name: getFileName(props.modelValue),
              status: "done",
              url: props.modelValue,
            },
          ]
        : []
    );
    const loading = ref<boolean>(false);
    const beforeUpload = (file: any) => true;
    const setFileUrl = (file: File, row: any) => {
      getFileLocalUrl(file)
        .then((url) => (row.thumbUrl = url))
        .catch((err) => console.log(err));
    };
    const selfUpload = async (target: any) => {
      loading.value = true;
      const fileItem = fileList.value[fileList.value.length - 1];
      setFileUrl(target.file, fileItem);
      let percent = 1;
      const setPercent = setInterval(() => {
        fileItem.percent = +((percent / (percent + 2)) * 100).toFixed(0);
        percent++;
      }, 100);
      try {
        const formData = new FormData();
        formData.append("file", target.file);
        const res: any = await userApi.uploadAvatar(formData);
        if (res.code === 200) {
          message.success($t("base.uploadSuccess"));
          fileItem.status = "done";
          fileItem.name = res?.data?.Key;
          fileItem.url = res?.data?.img_url;
          emit(
            "update:modelValue",
            fileList.value.map((item: any) => item.url).join(",")
          );
        } else {
          fileItem.status = "error";
          message.error(`${$t("base.uploadFailed")}: ${res.message}`);
        }
      } catch (error: any) {
        fileItem.status = "error";
        message.error(`${$t("base.uploadFailed")}: ${error.message}`);
      } finally {
        fileItem.percent = 100;
        clearInterval(setPercent);
        loading.value = false;
      }
    };
    const removeFile = (fileItem: any) => {
      fileList.value = fileList.value.filter(
        (item: any) => item.uid !== fileItem.uid
      );
      emit("update:modelValue", "");
    };
    return () => (
      <>
        <a-upload
          v-model:file-list={fileList.value}
          accept={props.accept}
          openFileDialogOnClick={true}
          disabled={loading.value}
          beforeUpload={beforeUpload}
          customRequest={selfUpload}
          onRemove={removeFile}
          maxCount={1}
        >
          <a-button>
            <upload-outlined></upload-outlined>
            {$t("base.uploadFile")} {fileList.value.length}/1
          </a-button>
        </a-upload>
      </>
    );
  },
});
